package com.xhwl.centiotdata.handler.org.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xhwl.centiotdata.handler.org.OrgFactory;
import com.xhwl.centiotdata.handler.org.OrgHandler;
import com.xhwl.centiotdata.pojo.dto.mili.FrameMiLiDTO;
import com.xhwl.centiotdata.pojo.dto.pedestrian.PedestrianIntegrationConfigDTO;
import com.xhwl.centiotdata.service.IOrgInfoService;
import com.xhwl.centiotdata.suppliersystem.mili.FrameMiLiHandler;
import com.xhwl.common.enums.OrganizationTypeEnum;
import com.xhwl.common.enums.ProductEnum;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.pojo.cent.iot.OrgInfo;
import com.xhwl.common.pojo.cent.sdata.Organization;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

/**
 * @description:
 * @author: wuyuhao
 * @createDate: 2022/10/18 17:51
 */
@Service
@Slf4j
public class OrgMiLiHandler extends OrgHandler {

    @Resource
    private IOrgInfoService iOrgInfoService;

    @Autowired
    private FrameMiLiHandler frameMiLiHandler;

    @Override
    public void afterPropertiesSet() throws Exception {
        // 米立人行
        OrgFactory.register(ProductEnum.MILI_PEDESTRIAN.getId(), this);
    }

    @Override
    public void createOrg(PedestrianIntegrationConfigDTO config, List<Organization> organizations) {
        organizations.forEach(org -> {
            if (org.getType() == OrganizationTypeEnum.ROOM.getId().intValue()) {
                // 将新的路址跟新生成的米立框架号做关联，并保存在数据库中
                this.createMiLiFrame(config, org);
            }
        });
    }

    @Override
    public void updateOrg(PedestrianIntegrationConfigDTO config, List<Organization> organizations) {
        organizations.forEach(org -> {
            if (org.getType() == OrganizationTypeEnum.ROOM.getId().intValue()) {
                // 如果需要更新的不存在，就创建
                OrgInfo one = iOrgInfoService.getOrgInfo(org.getId(), config.getProductId());
                if (ObjectUtils.isEmpty(one)) {
                    one = this.createMiLiFrame(config, org);
                }
                boolean editFrame = frameMiLiHandler.editFrame(org, config, one.getOrgIndexCode());
                if (!editFrame) {
                    throw new BusinessException("修改米立框架失败！");
                }
                log.info("修改米立框架成功！");
            }
        });
    }

    @Override
    public void deleteOrg(PedestrianIntegrationConfigDTO config, List<Organization> organizations) {
        organizations.forEach(org -> {
            if (org.getType() == OrganizationTypeEnum.ROOM.getId().intValue()) {
                // 如果需要删除的存在，才删除
                OrgInfo one = iOrgInfoService.getOrgInfo(org.getId(), config.getProductId());
                if (!ObjectUtils.isEmpty(one)) {
                    boolean delFrame = frameMiLiHandler.delFrame(config, one.getOrgIndexCode());
                    if (!delFrame) {
                        throw new BusinessException("删除米立框架失败！");
                    }
                    log.info("删除米立框架成功！");
                    iOrgInfoService.deleteOrgInfo(one.getId(), one.getProductId());
                    log.info("删除米立框架映射关系成功！");
                } else {
                    log.info("需要删除的米立框架映射关系不存在！");
                }
            }
        });
    }

    public OrgInfo createMiLiFrame(PedestrianIntegrationConfigDTO config, Organization org) {
        Integer productId = config.getProductId();
        String newFrameNO = getNewFrameNO(config);
        OrgInfo one = iOrgInfoService.getOrgInfo(org.getId(), productId);
        if (!ObjectUtils.isEmpty(one)) {
            iOrgInfoService.deleteOrgInfo(one.getId(), productId);
            log.info("已存在改米立框架的映射关系，数据删除成功！");
        }
        OrgInfo orgInfo = new OrgInfo();
        orgInfo.setId(org.getId());
        orgInfo.setParentId(org.getParentId());
        orgInfo.setOrgIndexCode(newFrameNO);
        orgInfo.setOrgName(org.getName());
        orgInfo.setProductId(productId);
        orgInfo.setEnterpriseId(org.getEnterpriseId());
        boolean save = iOrgInfoService.save(orgInfo);
        if (!save) {
            throw new BusinessException("保存米立映射关系失败！");
        }
        // 在米立中添加框架
        boolean b = frameMiLiHandler.addFrame(org.getType(), config, newFrameNO);
        if (!b) {
            throw new BusinessException("添加米立框架失败！");
        }
        log.info("添加米立框架成功！");
        return orgInfo;
    }

    public String getNewFrameNO(PedestrianIntegrationConfigDTO config) {
        JSONObject object = new JSONObject();
        object.put("ParentFrameNo", "0");
        object.put("Cascaded", true);
        List<FrameMiLiDTO> frameMiLiDTOList = frameMiLiHandler.queryFrame(config, object);
        Optional<Integer> optional = frameMiLiDTOList.stream()
                .filter(e -> !"9999".equals(e.getFrameNo())) // 9999 为区口顶级框架编号，过滤他
                .filter(e -> e.getFrameNo().length() >= 7) // 只需要房屋（01 01 0101）
                .map(e -> Integer.parseInt(e.getFrameNo()))
                .max(Integer::compareTo);
        if (optional.isPresent()) {
            int maxFrameNO = optional.get();
            // 如果房间号后四位是9998，那么要跳过9999
            if (maxFrameNO % 10000 == 9998) {
                maxFrameNO = maxFrameNO + 1;
            }
            return format(maxFrameNO + 1);
        } else {
            return format(1010101);
        }
    }

    private String format(int num) {
        int length = Integer.toString(num).length();
        int l = length % 2 == 0 ? length : length + 1;
        String pattern = "%0" + l + "d";
        return String.format(pattern, num);
    }
}
